package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信服务实现类
 *
 * @author: JBY
 * @since: 2025/08/20 10:35
 */
@Service
public class WechatServiceImpl implements WechatService {

    //OpenIdUrl
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    /**
     * 获取openid
     *
     * @param code
     * @return openId
     */
    @Override
    public String getOpenid(String code) {
        try {
            Map<String, Object> param = getParam();
            param.put("js_code", code);
            //返回的是字符串格式的JSON
            String result = HttpUtil.get(REQUEST_URL, param);
            //转化为JSON对象, 底层是map
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if (StrUtil.isNotEmpty(jsonObject.getStr("errcode"))) {
                throw new BaseException("网络繁忙, 请稍后再试.");
            }
            return jsonObject.getStr("openid");
        } catch (BaseException e) {
            throw new BaseException("网络繁忙, 请稍后再试.");
        }
    }

    /**
     * 获取手机号
     *
     * @param code
     * @return 手机号
     */
    @Override
    public String getPhoneNumber(String code) {
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("code", code);
            String result = HttpUtil.post(PHONE_REQUEST_URL + getToken(), JSONUtil.toJsonStr(param));
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if (jsonObject.getInt("errcode") != 0) {
                throw new BaseException("获取手机号失败");
            }
            return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        } catch (BaseException e) {
            throw new BaseException("网络繁忙, 请稍后再试.");
        }
    }

    /**
     * 获取token
     *
     * @return token
     */
    @Override
    public String getToken() {
        try {
            Map<String, Object> param = getParam();
            String result = HttpUtil.get(TOKEN_URL, param);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String accessToken = jsonObject.getStr("access_token");
            if (StrUtil.isNotEmpty(jsonObject.getStr("errcode"))) {
                throw new BaseException("获取AccessToken失败");
            }
            return accessToken;
        } catch (Exception e) {
            throw new BaseException("网络繁忙, 请稍后再试.");
        }
    }

    /**
     * 获取参数
     *
     * @return 参数
     */
    private Map<String, Object> getParam() {
        Map<String, Object> param = new HashMap<>();
        param.put("appid", appid);
        param.put("secret", secret);
        return param;
    }
}
